package action;

import java.util.Map;

import model.User;

import org.apache.struts2.interceptor.SessionAware;

import service.PositionService;
import service.UserService;
import util.DataUtil;
import util.ValidateUtil;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class LoginAction extends ActionSupport implements SessionAware,
ModelDriven<User>, Preparable {
	private static final long serialVersionUID = 1L;
	private UserService userService;
	
	public void setUserService(UserService userService) {
		this.userService = userService;
	}	
	
	/**
	 * 登陆操作
	 */
	public String login(){
		
		return "login";
	}
	
	public String doLogin(){
			if(!ValidateUtil.isValid(model.getEmail())){
				this.addFieldError("email","邮箱不能为空!");
				return "login";
			}
			if(!ValidateUtil.isValid(model.getPassword())){
				this.addFieldError("email","密码不能为空!");
				return "login";
			}
			String s1 = DataUtil.MD5(model.getPassword());
			if(userService.getUserByEmail(model.getEmail()) != null){
				String s2 = userService.getUserByEmail(model.getEmail()).getPassword();				
				if(s1.equals(s2)){
					User user = userService.getUserByEmail(model.getEmail());
					session.put("user", user);
					return SUCCESS;
				}else{
					this.addFieldError("email","邮箱或密码错误!");
					return "login";
				}
			}else{
				this.addFieldError("email","邮箱或密码错误!");
				return "login";
			}
	}
	
	/**
	 * 登出操作
	 */
	public String logout(){
		session.put("user", null);
		return SUCCESS;
	}

	@Override
	public void prepare() throws Exception {
		// TODO Auto-generated method stub
		
	}

	private User model = new User();
	
	@Override
	public User getModel() {
		// TODO Auto-generated method stub
		return model;
	}

	private Map<String, Object> session;
	
	@Override
	public void setSession(Map<String, Object> arg0) {
		// TODO Auto-generated method stub
		this.session = arg0;
	}

	
	
}
